<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules">
      <el-form-item prop="userName">
        <el-input v-model="loginForm.userName" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          placeholder="密码"
          @keyup.enter="handleLogin"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox label="记住我" v-model="loginForm.rememberMe" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin" class="login-button">登录</el-button>
      </el-form-item>
      <el-form-item>
        <router-link to="/register">立即注册</router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { useLoginStore } from '@/stores/loginStore'
import { request } from '@/utils/request'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import Cookies from 'js-cookie'

const router = useRouter()
const loginStore = useLoginStore()

const loginRef = ref(null)
const loginForm = ref({
  userName: 'liarjo2',
  password: '123456',
  // userName: '',
  // password: '',
  rememberMe: false,
})
const loginRules = {
  userName: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
}

const handleLogin = async () => {
  await loginRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (loginForm.value.rememberMe) {
          Cookies.set('userName', loginForm.value.userName, { expires: 30 })
          Cookies.set('password', loginForm.value.password, { expires: 30 })
          Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 })
        } else {
          Cookies.remove('username')
          Cookies.remove('password')
          Cookies.remove('rememberMe')
        }
        const response = await request.post('/api/login', loginForm.value)
        loginStore.setLoginInfo(response)
        router.push('/')
      } catch (error) {
        ElMessage.success({
          message: error.message,
          duration: 2000,
        })
      }
    }
  })
}
// rememberMe
const rememberMe = () => {
  loginForm.value = {
    userName: Cookies.get("userName"),
    password: Cookies.get("password"),
    rememberMe: !!Cookies.get("rememberMe")
  };
}
rememberMe();
</script>

<style lang="scss" scoped>
.login {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  .login-button{
    width: 100%;
  }
}
</style>
